package com.mopaas.test.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.mopaas.test.msg.MsgEnums;

public class Result {

	private static Logger logger = Logger.getLogger(Result.class);
	private Map<String, Object> result = new HashMap<String, Object>();

	public Result() {
		result.put("code", MsgEnums.C_00001.name());
		result.put("msg", MsgEnums.C_00001.getMessage());
	}

	public void setCodeAndMsg(String code, String msg) {
		result.put("code", code);
		result.put("msg", msg);
	}

	public void add(String key, Object value) {
		result.put(key, value);
	}

	public void addList(List<?> list) {
		result.put("list", JsonUtils.toJSON(list));
	}

	public void addResult(Object obj) {
		if (obj instanceof String) {
			result.put("result", obj);
		} else {
			result.put("result", JsonUtils.toJSON(obj));
		}
	}

	public Map<String, Object> returnResult() {
		return result;
	}

	public void asynchronousPrintResult(HttpServletResponse response,
			Object value) {
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = null;
		try {
			writer = response.getWriter();
			writer.print(JsonUtils.toJSON(value));
			writer.flush();
			writer.close();
		} catch (IOException e) {
			logger.error("asynchronousPrintResult error!" + e);
		}
	}
}
